//
//<script language=javascript>


var mywindow = ""; //used to open the dropcal
var mywindowclosed = true; //test if dropcal window is open
var currencyDigits = {BHD:3, BIF:0, BYR:0, CLP:0, DJF:0, GNF:0, IQD:3, ISK:0, JOD:3, JPY:0, KMF:0, KRW:0, KWD:3, LYD:3, OMR:3, PYG:0, RWF:0, TND:3, TRL:0, VUV:0, XAF:0, XOF:0, XPF:0};
var currencySymbols = {USD:'$',EUR:'&euro;',GBP:'&pound;'};

if (!window.CNQR) {window.CNQR = {}}
window.CQJSerrors = {}; // error dict so we don't get spammed with errors


function checkFocus()
{
    if (mywindow == null || typeof(mywindow) == 'undefined') { return }

	try {
		if (!mywindow.closed && !mywindowclosed)
		{
			mywindow.focus();
		}
	}
	catch (e) {/*ignore error*/}
}

function otTrim(str)
{
    var tmpStr = str;
    tmpStr = tmpStr.replace(/^\s*/, "");
    tmpStr = tmpStr.replace(/\s*$/, "");
    return tmpStr;
}

// Check that a string contains only letters
function isAlphabetic(string, ignoreWhiteSpace) {
	if (string.search) {
		if ((ignoreWhiteSpace && string.search(/[^a-zA-Z\s]/) != -1) || (!ignoreWhiteSpace && string.search(/[^a-zA-Z]/) != -1)) return false;
	}
	return true;
}

// Check that a string contains only digits (0-9) and intervening white spaces
// (This is not to be used to check for numeric-ness since numeric should include negative sign and decimal point)
function hasOnlyDigits(string) {
	if (string.search) {
		if (otTrim(string).search(/[^0-9\s]/) != -1) return false;
	}
	return true;
}

function JSPadOut(iInt)
{
	if (iInt < 10)
	{
		iInt = "0" + iInt;
	}
	return iInt;
}

function openHelp(page, anchor)
{
	var screenLeft = screen.width/2 - 750;
	var screenTop = screen.height/2 - 550;
	var strAttributes = "width=750,height=550,left=" + screenLeft + ",top=" + screenTop + ",scrollbars=1,resizable=1,location=0,status=0,toolbar=0";

    helpwindow = window.open('/help/help_frame.asp?page=' + escape(page) + '&anchor=' + escape(anchor), 'help', strAttributes);
    helpwindow.focus();
}

function setDDIndexByValue(box, sValue)
{

	for (var i=0;i<box.length;i++)
	{
		if (box.options[i].value == sValue)
		{
			box.selectedIndex = i;
			break;
		}
	}
}

function setDDIndexByText(box, sText)
{
	for (var i=0;i<box.length;i++)
	{
		if (box.options[i].text == sText)
		{
			box.selectedIndex = i;
			break;
		}
	}
}

function setDDIndexToDefault(box)
{
	for (var i=0;i<box.length;i++)
	{
		if (box.options[i].defaultSelected)
		{
			box.selectedIndex = i;
			break;
		}
	}
}

var g_ppw_URL = '';
var g_ppw_Name = '';
var g_ppw_Parms = '';
var g_ppw_windowHandleName;
var g_ppw_pleaseWaitPageURL = '/common/processing_holder.asp';


function popupWindow(mypage, myname, w, h, otherParms)
{
	mypage = mypage.replace(/\+/g, '%2B')
	// due to problems with + sign in IE5 getting unescaped,
	//I replaced '+' with the urlencoded value for +
	//pops up a window in the center
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;

	var sParms;
	if (typeof(otherParms) != 'undefined' && otherParms != 'yes' && otherParms != 'no'){
	    sParms = otherParms;
	}
	else{
	    sParms = 'scrollbars=1,resizable=1';
	}

	winprops = 'height=' + h + ',width=' + w + ',top=' + wint + ',left=' + winl + ',' + sParms;

	g_ppw_URL = mypage;
	g_ppw_Name = myname;
	g_ppw_Parms = winprops;
	g_ppw_windowHandleName = 'mywindow';

	//try to open the window
	try
	{
		mywindow = window.open(g_ppw_pleaseWaitPageURL, myname, winprops);
	}
	catch(e) {}

	if(!testPopupWindow(mywindow))
	{
		window.setTimeout("makePopupBlockerDiv()", 1);
	}
	else
	{
		try
		{
			window.setTimeout('if(!(testPopupWindow(mywindow))) {makePopupBlockerDiv()} else {mywindow.document.location.replace("' + mypage + '")}', 100);
		}
		catch(e)
		{
			makePopupBlockerDiv();
			return;

		}
		// next call is disabled for NS6, which generates an error ("component does not have requested interface")
		if ((parseInt(navigator.appVersion) >= 4) && (!document.getElementById) && mywindow) { mywindow.window.focus(); }
	}

	mywindowclosed = false;
}

function testPopupWindow(windowObj)
{
	var reTestPopup	= new RegExp('object','gi');
	var isClosed = true;

	var isAlive = reTestPopup.test(String(windowObj));

	if (isAlive)
	{
		try
		{
			//check to see if the window is actually open
			isClosed = windowObj.closed;
		}
		catch(e)
		{
			isClosed = true;
		}

		if (isClosed) isAlive = false;
	}

	return isAlive;
}

function redoPopupWindow()
{
	if (g_ppw_URL != '')
	{
		var ppw_NewWindow = window.open(g_ppw_URL,g_ppw_Name, g_ppw_Parms);

		if (g_ppw_windowHandleName != null && g_ppw_windowHandleName != '')
		{
			eval(g_ppw_windowHandleName + ' = ppw_NewWindow');
		}

		g_ppw_URL = '';
		g_ppw_Name = '';
		g_ppw_Parms = '';
		g_ppw_windowHandleName = '';
	}

	var popupblockerfound = document.getElementById('div_popupblockerfound');
	popupblockerfound.style.display = 'none';
}


function makePopupBlockerDiv()
{
	var w = '400';
	var h = '200';

	var popupblockerdiv = document.getElementById('div_popupblockerfound');
	if (popupblockerdiv)
	{
		popupblockerdiv.style.display = 'block';
		popupblockerdiv.style.left = (document.body.clientWidth-w)/2;
		popupblockerdiv.style.top = (document.body.clientHeight-h)/2 - 50;
	}
	else
	{
		//Then this div does not exist, so create it.

		var sHTML = '<p>' + OTGetUserMessage("SmallJs", "PopupBlocker1") + '<p/>';
		sHTML+= '<p>' + OTGetUserMessage("SmallJs", "PopupBlocker2") + '<br/>';
		sHTML+= '<ul><li>http://' + document.location.host + '</li></ul></p>';
		sHTML+= '<p style="text-align:center;"><input type="button" onclick="redoPopupWindow()" value="OK" name="ot_pblocker"></p>';


		var v=document.createElement('div');

		v.setAttribute('id',"div_popupblockerfound");
		v.setAttribute('tabindex',"-1");
		v.setAttribute('aria-live',"assertive");
		v.style.position='absolute';
		v.style.width=w+'px';
		v.style.height=h+'px';
		v.style.padding='10px';
		v.style.border='double red';
		v.style.backgroundColor='white';
		v.style.textAlign='left';
		v.style.fontFamily = 'arial';
		v.style.fontSize='9pt';
		v.style.zIndex='9997';

		v.innerHTML = sHTML;

		//center it

		v.style.left = (document.body.clientWidth-w)/2;
		v.style.top = (document.body.clientHeight-h)/2 - 50;

		document.body.appendChild(v);
	}
	
	// 508 - For screen readers to go right to the popup notice, and tab to go to the OK button
	// Timeout is to give the popup time to be created and attached to page
	window.setTimeout(function() {
		$('div_popupblockerfound').focus();
		$('div_popupblockerfound').innerHTML = $('div_popupblockerfound').innerHTML;
		}, 200);
}

function test_popupBlocker()
{
	//set your window handle to g_ppw_windowHandleName after popping up a window.

	if (typeof(g_ppw_windowHandleName) != 'string') alert('DEVELOPER -- PLEASE USE A STRING FOR g_ppw_windowHandleName.\n e.g. g_ppw_windowHandleName = \'mywindow\'  ');

	var ppw_NewWindow = (g_ppw_windowHandleName == '') ? null : eval(g_ppw_windowHandleName);

	if ( (ppw_NewWindow==null) || (typeof(ppw_NewWindow)=="undefined") || ppw_NewWindow.closed == true )
	{
		makePopupBlockerDiv();
	}
}

function getSelectedVal(formObj)
{
	//take a drop down (select), return the value

	if (!formObj) return;
	return formObj.options[formObj.options.selectedIndex].value;
}

function getMultiSelectValuesArray(sel) {
    function selectedOptions(o) {
        return o.selected;
    }
    return $A(sel.options).findAll(selectedOptions).pluck('value');
}

function getMultiSelectValuesList(sel) {
    var valList = "";
    $A(sel.options).each(function(o) {
        if (o.selected) {
            if (valList == "") valList += ",";
            valList += o.value + ",";
        }
    })
    return valList;
}

function getRadioVal(formObj)
{
	//take a radio button, return the value
	//of the first checked one.

	if (!formObj) return;

	if (formObj.length)
	{
		for (var i=0;i < formObj.length;i++)
		{
			if (formObj[i].checked)
			{
				return formObj[i].value;
				break;
			}
		}
	}
	else
	{
		return formObj.value
	}
}

function setRadioVal(formObj, val)
{
	//take a radio button, set the value
	//of the first one found to checked.

	if (!formObj) return;

	if (formObj.length)
	{
		for (var i=0;i < formObj.length;i++)
		{
			if (formObj[i].value == val)
			{
				if (!formObj[i].checked)
					 formObj[i].click();
				break;
			}
		}
	}
	else
	{
		return formObj.checked = true;
	}
}

function JS_FormatNumber(theNum, decPlaces, format)		// Parameter 'format' = PreferenceNumberFormat session variable
{														// Not dealing with thousands separator yet (1/24/2001)
	GetNumberSeparators(format);

	if (!format) {
		format = (window['userNumberPreference'] || 0)
	}

	theNum = parseFloat(theNum);
	decPlaces = parseInt(decPlaces,10);

	if (isNaN(theNum)) {
		theNum = 0.0;
	}

	var wasNegative = false
	if (theNum < 0) {
		theNum = -1.0*theNum;
		wasNegative = true;
	}

	// address known issue with IEEE float numbers that end in #.##..#5 that can't be represented correctly.
	var useFudge = false;
	var tmpNum = theNum.toString();
	var decPos = tmpNum.indexOf('.');
	if (decPos > -1) {
		var nextN = tmpNum.substr(decPos+1, decPlaces+1);
		if (nextN.length == decPlaces+1) {
			if (nextN.substr(nextN.length-1,1) == '5') {
				useFudge = true;
			}
		}
	}

	var strNum;

	if (useFudge == true) {
		strNum = "" + Math.round((theNum * Math.pow(10,decPlaces))+.01);
	}
	else {
		strNum = "" + Math.round(theNum * Math.pow(10,decPlaces));
	}

	while (strNum.length <= decPlaces)
	{
		strNum = "0" + strNum;
	}

	var decPoint = strNum.length - decPlaces;

	var formattedNumber = strNum.substring(0,decPoint);

	// only add decimals if we are formatting to at least one decimal place
	if (decPlaces > 0) {
		formattedNumber += decSep + strNum.substring(decPoint,strNum.length);
	}

	if (wasNegative) {
		formattedNumber = "-" + formattedNumber;
	}

	return formattedNumber;
}

function JS_UnformatNumber(theNum, format) // Parameter 'format' = PreferenceNumberFormat session variable
{
	GetNumberSeparators(format)

	// Turn decimal separators to periods
	var strRegex = new RegExp("\\" + decSep, "g")
	theNum = theNum.replace(strRegex, '.')

	// Strip thousands separators
	strRegex.compile("\\" + thouSep, "g")
	var tmpNum = theNum.replace(strRegex, '')

	if (isNaN(tmpNum))
	{
		alert(OTGetUserMessage("SmallJs", "CheckIfValidNumber"));
		return false;
	}

	var arrNum = theNum.split(".")
	if (arrNum.length == 2 && arrNum[1] != "") // Decimal values entered
	{
		// Check for chars other than digits to the right of the decimal
		strRegex.compile("[^\\d]")
		if (strRegex.test(arrNum[1]))
		{
			alert(OTGetUserMessage("SmallJs", "CheckIfValidNumber"));
			return false;
		}
	}
	// Check for proper separation of thousands separators left side of number, if present
	if(arrNum[0].indexOf(thouSep) >= 0)
	{
		var arrNumLeft = arrNum[0].split(thouSep)

		for (var i=1;i<arrNumLeft.length;i++)
		{
			if (arrNumLeft[i].length != 3)
			{
				alert(OTGetUserMessage("SmallJs", "CheckPlacementThouSeparator"));
				return false;
			}
		}
	}

	// Strip out thousands character and return number
	strRegex.compile("\\" + thouSep, "g")
	return theNum.replace(strRegex, '')
}

function JS_FormatMoney2(money, currency, format) {
	if (format == null) format = (window['userNumberPreference'] || 0)
	return JS_FormatMoney(money, format, currency);
}
function JS_FormatMoney(money, format, currency) // Parameter 'format' = PreferenceNumberFormat session variable
												//Parameter 'currency' = PreferenceDefaultCurrency and is optional
{
	var digits = (currencyDigits[currency] == null) ? 2 : currencyDigits[currency];

	//var currencySymbol = currencySymbols[currency] || currency;
	if (currency == null)
	{
		return JS_FormatNumber(money,digits,format)
	}
	else if (typeof(currency) != 'undefined' && currency != 'USD')
	{
		return currency + JS_FormatNumber(money,digits,format)
	}
	else
	{
		return "$" + JS_FormatNumber(money,digits,format)
	}
}


function JS_UnformatMoney(money, format, currency)  // Parameter 'format' = PreferenceNumberFormat session variable
													//Parameter 'currency' = PreferenceDefaultCurrency and is optional
{
	money = money.replace(/\$/g, '')
	if (typeof(currency) != 'undefined')
	{
		var strRegex
		if (currency.length == 3) {
			strRegex = new RegExp(currency, "g")
		} else {
			strRegex = new RegExp("\\" + currency, "g")
		}
		money = money.replace(strRegex, '')
	}
	return  JS_UnformatNumber(money, format);
}

var thouSep, decSep
function GetNumberSeparators(format)
{
    if(format)
    {
        format = format.toString();
    }
    switch(format)
	{
		case "0":	// 1,000.00
			thouSep = ",";
			decSep = ".";
			break;
		case "1":	// 1.000,00
			thouSep = ".";
			decSep = ",";
			break;
		case "2":	// 1 000,00
			thouSep = " ";
			decSep = ",";
			break;
		case "3":	// 1'000.00
			thouSep = "'";
			decSep = ".";
			break;
		case "4":	// 1'000,00
			thouSep = "'";
			decSep = ",";
			break;
		default:	// default to NA-stype (0)
			thouSep = ",";
			decSep = ".";
			break;
	}
}


CNQR.getMoneyDecimalDigits = function(currencyCode)
{
	var digits = (window.currencyDigits && window.currencyDigits[currencyCode] != null) ? window.currencyDigits[currencyCode] : 2;
	return digits;
}

CNQR.getDecimalSeparator = function(numberFormat)
{
	GetNumberSeparators(numberFormat);
	return decSep;
}

CNQR.formatMoney = function (theNum, currencyCode, numberFormat)
{
	var digits = (window.currencyDigits && window.currencyDigits[currencyCode] != null) ? window.currencyDigits[currencyCode] : 2;

	var strNum = CNQR.formatNumber(theNum, digits, numberFormat, window.negativeCurrencyFormat);
	if ((typeof(currencyCode) != 'undefined') && (currencyCode != null))
	{
		//VB Script functions and JS_formatMoney don't use space between amount and currency code
		//but that makes it difficult to read when it's anything other than a symbol
		//so this will put in a space if not using symbol

        var currencySymbol = currencySymbols[currencyCode] || currencyCode;

        if(currencySymbol.length == 1 && currencyCode != defaultEmpCurrencyCode)
            currencySymbol = currencyCode;

        var space = (currencySymbol.length == 3)?" ":"";

		if (window.currencySymbolLocation) {
			strNum = strNum + space + currencySymbol;
		}
		else {
			strNum = currencySymbol + space + strNum;
		}
	}
	return strNum;
}

CNQR.formatMoneyWithoutSymbol = function (theNum, currencyCode, numberFormat, canReturnBlank, hideCurrency)
{
    if (((isNaN(theNum)) || (theNum == null)) && canReturnBlank)
    {
		return "";
	}
	
	var digits = (window.currencyDigits && window.currencyDigits[currencyCode] != null) ? window.currencyDigits[currencyCode] : 2;

	var strNum = CNQR.formatNumber(theNum, digits, numberFormat, window.negativeCurrencyFormat);
	if (!hideCurrency && (typeof(currencyCode) != 'undefined') && (currencyCode != null))
	{
		strNum = strNum + " " + currencyCode;
	}
	return strNum;
}

CNQR.formatNumber = function (theNum, decPlaces, numberFormat, negativeFormat)
{
    //Always call formatnumber/formatdate with a number/date constructed in locale-neutral format e.g (YYYY/MM/DD) or (XXXX.XX)
    //return JS_FormatNumber(theNum, decPlaces, window.userNumberPreference || 0);

    //GetNumberSeparators is in Outtask Web Public\javascript\functions.js and will set thouSep, decSep

    if ((typeof(numberFormat) == "undefined") || (numberFormat == null)) //0 is valid, so don't want to just check " if (numberFormat) "
	{
		numberFormat = window.userNumberPreference || 0;
	}

	if ((typeof(negativeFormat) == "undefined") || (negativeFormat == null))
	{
		negativeFormat = window.negativeNumberFormat || 0;
	}


	GetNumberSeparators(numberFormat);

    if ((isNaN(theNum)) || (theNum == null))
    {
		theNum = 0.0;
	}

	var wasNegative = false;
	if (theNum < 0) {
		theNum = -1.0*theNum;
		wasNegative = true;
	}

	// address known issue with IEEE float numbers that end in #.##..#5 that can't be represented correctly.
	var useFudge = false;
	var tmpNum = theNum.toString();
	var decPos = tmpNum.indexOf('.');
	if (decPos > -1) {
		var nextN = tmpNum.substr(decPos+1, decPlaces+1);
		if (nextN.length == decPlaces+1) {
			if (nextN.substr(nextN.length-1,1) == '5') {
				useFudge = true;
			}
		}
	}

	var strNum;
	if (useFudge == true) {
		strNum = "" + Math.round((theNum * Math.pow(10,decPlaces))+.01);
	}
	else {
		strNum = "" + Math.round(theNum * Math.pow(10,decPlaces));
	}

	while (strNum.length <= decPlaces)
	{
		strNum = "0" + strNum;
	}

	var decPoint = strNum.length - decPlaces;

	var formattedNumber = strNum.substring(0,decPoint);

	var newInt  = "";
    var tmpS = formattedNumber;

    while (tmpS.length >3)
    {
			newInt = thouSep + tmpS.substring(tmpS.length-3, tmpS.length)  +  newInt;

			tmpS = tmpS.substring(0, tmpS.length - 3);
    }
    formattedNumber  = tmpS + newInt ;

	// only add decimals if we are formatting to at least one decimal place
	if (decPlaces > 0) {
		formattedNumber += decSep + strNum.substring(decPoint,strNum.length);
	}

	if (wasNegative) {
		if (window.negativeNumberFormat) {
			formattedNumber = "(" + formattedNumber +")";
		}
		else {
			formattedNumber = "-" + formattedNumber;
		}
	}

    return formattedNumber;

}

CNQR.unFormatNumber = function (theNum)
{
    //Always call the unformat functions with a user preferred date/number(based on the userpref global variables)
    if (theNum == null)
        return null;

	if (typeof(theNum) == "undefined")
        return null;

	if (typeof(theNum) != "string")
        theNum = theNum.toString();

	// MAN-821: If number/money field is being cleared out, need to return empty string so that field will be sent
    // to server
    theNum = otTrim(theNum);
    if (theNum == "")
        return "";

    //GetNumberSeparators is in Outtask Web Public\javascript\functions.js and will set thouSep, decSep
	GetNumberSeparators(window.userNumberPreference || 0);

    isNegative = false;
    if ((theNum.indexOf("(") == 0) || (theNum.indexOf("-") == 0))
    {
        isNegative  = true;
	    var strRegex = new RegExp("\\(|\\)|\\-", "g");
	    theNum = theNum.replace(strRegex, '')
    }

    var whole, fraction;
    var decloc = theNum.indexOf(decSep);
	if (decloc == -1)
	{
		/* no decimal seperator in number */
		whole = theNum;
		fraction = "0";
	}
	else
	{
		fraction = theNum.substr(decloc + 1);
		whole = theNum.substring(0, decloc);
	}
	var re = new RegExp("\\" + thouSep, "g");
	whole = whole.replace(re, "");
    if (whole.length == 0)
    {
        whole = "0";
    }
	if (fraction != "0")
	{
		whole = whole + "." + fraction;
	}
	if (isNaN(whole))
	{
        return null;
	}

    if (isNegative == false)
	    return parseFloat(whole);
    else
	    return -1*parseFloat(whole);


}


function populateDDWithArray(arr, box, defaultVal)
{
	var maxnum = arr.length;
	box.options.length=0;
	for (var i=0;i<maxnum;i++)
	{
		var no = new Option();
		no.value = i;
		no.text = arr[i];
		box.options[box.options.length] = no;
		if (defaultVal == i) box.options[box.options.length -1].selected = true;
	}
}

function populateDDWithCollection(dict, box, defaultVal)
{
	var key;
	box.length = 0;
	for (key in dict) //ac-ok
	{
		if (otHasOwnProperty(dict, key))
		{
			var no = new Option();
			no.value = key
			no.text = dict[key]
			box.options[box.options.length] = no;
			if (defaultVal == key) box.options[box.options.length -1].selected = true;
		}
	}
}
function populateDDWith2dArray(box, arr, fk, defaultVal)
{
	var key
	box.length = 0;
	for (key in arr)  //ac-ok
	{
		if (otHasOwnProperty(arr, key) && fk == arr[key][0])
		{
			var no = new Option();
			no.value = key
			no.text = arr[key][1]
			box.options[box.options.length] = no;
			if (defaultVal == key) box.options[box.options.length -1].selected = true;
		}
	}
}

function populateDDWith3dArray(box, arr, fk, defaultVal)
{
	var key
	box.length = 0;
	for (key in arr)  //ac-ok
	{
		if (otHasOwnProperty(arr, key) && fk == arr[key][0])
		{
			var no = new Option();
			no.value = arr[key][2]
			no.text = arr[key][1]
			box.options[box.options.length] = no;
			if (defaultVal == key) box.options[box.options.length -1].selected = true;
		}
	}
}

function imgPreload() {
	var ar = new Array();
	var arguments = imgPreload.arguments;
	for (var i = 0; i < arguments.length; i++)
	{
		ar[i] = new Image();
		ar[i].src = arguments[i];
	}
}

// Simple function to return a numeric value from style like "23px"
function intValueFromStyle(styleAmt)
{
	return parseInt(styleAmt.replace("px", ""));
}

// Cross-browser event attachment & removel for IE5+ & NS6
// evType - event, ie., "mouseover", "click", "focus"
// fn - function name
// useCapture - BOOLEAN - for NS6 & equivelents only - hijack the event before it reaches target,

function addEvent(obj, evType, fn, useCapture){

/*
	if (evType == 'load' && obj === window) {
		otDomReady.addOnLoad(fn);
		return true;
	}
*/

	if (window.Event && Event.observe) { //use prototype if available for memory cleanup
		return Event.observe(obj, evType, fn, useCapture);
	}

	if (evType == 'keypress' && (navigator.appVersion.match(/Konqueror|Safari|KHTML/) || obj.attachEvent)) {
		evType = 'keydown';
	}

  if (obj.addEventListener){
    obj.addEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be attached");
  }

}

function removeEvent(obj, evType, fn, useCapture){

	if (window.Event && Event.stopObserving) { //use prototype if available
		Event.stopObserving(obj, evType, fn, useCapture)
	}

	if (evType == 'keypress' && (navigator.appVersion.match(/Konqueror|Safari|KHTML/) || obj.detachEvent)) {
		evType = 'keydown';
	}


  if (obj.removeEventListener){
    obj.removeEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.detachEvent){
    var r = obj.detachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be removed");
  }
}

// From quirksmode
// The last two lines handle Safari. If an event takes place on an element that contains text,
// this text node, and not the element, becomes the target of the event.
// If nodeType is 3, a text node. If it is we move to its parent node, the HTML element.
function getEventTarget(e) {
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
	return targ;
}


function loadXA(url)
{
	if (!document.getElementById)
	{
		alert(OTGetUserMessage("SmallJs", "XARequiresRealBrowser"));
		return false;
	}
	window.open(url,'AgentTool','width=160,height=' + window.screen.availHeight + ',top=0,left=' + (window.screen.availWidth-160) + ',scrollbars=0,resizable=1,history=0');
}

function exists(elem)
{
	return (typeof(elem) != "undefined") ? true : false;
}

function isEven(x) { return (x%2)?false:true; }

/*
The following two functions allow you to warn users who are leaving an altered form without saving.
To use:
1. Set your page's onbeforeunload property:

	document.body.onbeforeunload = "LeavePageIfDirty(document.frmMain)"

2. Change your page's submit function to disable the property
	(so the user isn't warned when submitting):

	document.body.onbeforeunload = "";
	document.frmMain.submit();
*/

function LeavePageIfDirty(theForm)
{
	var msg =  OTGetUserMessage("SmallJs", "ChangedFormDataWillBeLost")
	if(IsFormDirty(theForm)){
		event.returnValue = msg;
	}
}

function LeavePageIfDirtyWithEvent(event, theForm){
	var msg =  OTGetUserMessage("SmallJs", "ChangedFormDataWillBeLost")
	if(IsFormDirty(theForm)){
		event.returnValue = msg;
	}
}


function IsFormDirty(theForm){
	var isDirty = false;
	var debug = false; //for debugging -- throws messages at you so you know what fields are trigging "is dirty".
	var myForm = theForm.elements;
	var count = 0; //just counting fields
	for (var i=0; i < myForm.length; i++){
		//igore any hidden, disabled, or readonly fields
		if (!myForm[i].disabled && !myForm[i].hidden && !myForm[i].readOnly){
			//Check checkboxes
			if (myForm[i].type == 'checkbox' && myForm[i].checked != myForm[i].defaultChecked)
			{
				if (debug) alert(myForm[i].type + ": " + myForm[i].name + " has changed!\n it was:" + myForm[i].defaultChecked + ",\n but it's now " + myForm[i].checked);
				isDirty = true;
				count = count + 1;
			}
			//Check text fields and textareas
			if ((myForm[i].type == 'text' || myForm[i].type == 'textarea') && myForm[i].value != myForm[i].defaultValue)
			{
				if (debug) alert(myForm[i].type + ": " + myForm[i].name + " has changed!\n it was:\n" + myForm[i].defaultValue + "\n but it's now:\n " + myForm[i].value);
				isDirty = true;
				count = count + 1;
			}
			//check select-single drop-downs
			if (myForm[i].type == 'select-one' || myForm[i].type == 'select-multiple')
			{
				if(isSelectDirty(myForm[i]))
				{
					isDirty = true;
					count++;
				}
			}
			//Check radio buttons
			if (myForm[i].type == 'radio')
			{
				for (var j = 0; j < myForm[i].length; j++)
				{
					var vIs="", vWas="";
					for (var j = 0; j < myForm[i].options.length; j++){
						if(myForm[i].options[j].checked) {vIs = myForm[i].options[j].value}
						if(myForm[i].options[j].defaultChecked) {vWas = myForm[i].options[j].value}
					}
					if (vIs != vWas)
					{
						if (debug) alert(myForm[i].type + ": " + myForm[i].name + " has changed\n it was:\n" +
							vWas + "\n but it's now:\n " + vIs);
						isDirty = true;
						count = count + 1;
					}

				}
			}

			//Check for Script.acolo.us "Draggable" ordered lists
			//Uses a hidden form item placeholder to point to a list for checking
			if (myForm[i].type == 'hidden' && myForm[i].className == 'orderChangePlaceholder')
			{
				var questionHolder = document.getElementById(myForm[i].value);
				for (var j = 0; j < questionHolder.childNodes.length; j++){
					if (questionHolder.childNodes[j].getAttribute('originalOrder') != (j+1)) {
						isDirty = true;
					}
				}
			}
		}
	}
	if(isDirty && debug) {alert(count + ' dirty fields.')}
	return isDirty;
}

function isSelectDirty(sel)
{
	var debug = false;
	if (sel.type == 'select-one')
	{
		var vIs=0, vWas=0;
		for (var j = 0; j < sel.options.length; j++){
			if(sel.options[j].selected) {vIs = j}
			if(sel.options[j].defaultSelected) {vWas = j}
		}
		if (vIs != vWas)
		{
			if (debug) alert(sel.type + ": " + sel.name + " has changed\n it was:\n" + vWas + "\n but it's now:\n " + vIs);
			return true;
		}
	}
	//check multi-select boxes
	if (sel.type == 'select-multiple')
	{
		for (var j = 0; j < sel.options.length; j++)
		{
			if(sel.options[j].defaultSelected != sel.options[j].selected)
			{
				if (debug) alert(sel.type + ": " + sel.name + " has changed!");
				return true;
			}
		}
	}
	return false;
}

// Checkes if the enter key is pressed.
// Usage example:  <input type="text" name="foo" value="" onKeyDown="if enterPressed(event) doSomething();">
function enterPressed(evt) {
	evt = (evt) ? evt : event;
	var charCode = (evt.charCode) ? evt.charCode :
		((evt.which) ? evt.which : evt.keyCode);
	if (charCode == 13 || charCode == 3) {
		return true;
	} else {
		return false;
	}
}

function OTDebugWrite(aMessage) {
	var h = document.location.host.toLowerCase();
	if (h.substr(0, 3) != 'www' && h.substr(0, 4) != 'app2') {
		try {
			console.log(aMessage);
		}
		catch(e) {
			var tempDiv = document.getElementById("DEBUGDIVXXXYYYZZZ");
			if (tempDiv == null) {
				var tempDiv = document.createElement('div');
				tempDiv.setAttribute('id', "DEBUGDIVXXXYYYZZZ");
				tempDiv.className = "OTDEBUG";
				tempDiv = document.body.insertBefore(tempDiv, document.body.firstChild);
				tempDiv.defaultHTML = '<b>DEBUG WINDOW</b>&nbsp;<a href="javascript:void(0);" style="color:white;" onclick="$(\'DEBUGDIVXXXYYYZZZ\').innerHTML = $(\'DEBUGDIVXXXYYYZZZ\').defaultHTML;">Clear Result</a><br/>'
				tempDiv.innerHTML = tempDiv.defaultHTML;
				tempDiv.ondblclick = function() { tempDiv.style.display = 'none'; }
			}
			var tmpTxt = document.createElement('p');
			tmpTxt.innerHTML = aMessage;
			tempDiv.appendChild(tmpTxt);
			tempDiv.style.display = '';
			tempDiv.scrollTop = tempDiv.scrollHeight;
		}
	}
}

//the following three were borrowed from prototype.js (MIT license)
function $() {
  var elements = new Array();

  for (var i = 0; i < arguments.length; i++) {
    var element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);

    if (arguments.length == 1)
      return element;

    elements.push(element);
  }

  return elements;
}

Function.prototype.bind = function(object) {
	var __method = this;
	return function() {
		return __method.apply(object, arguments);
	}
}

Function.prototype.bindAsEventListener = function(object) {
	var __method = this;
	return function(event) {
		return __method.call(object, event || window.event);
	}
}

String.format = function(_str) {
	//ripped from ExtJS
    var values = Array.prototype.slice.call(arguments,1);
    return _str.replace(/\{(\d)\}/g,function(){
        return values[arguments[1]];
    })
}

Object.extend = function(destination, source) {
  for (property in source) {
    destination[property] = source[property];
  }
  return destination;
}

function stopEvent(event)
{
	if (event.preventDefault) {
		event.preventDefault();
		event.stopPropagation();
	} else {
		event.returnValue = false;
		event.cancelBubble = true;
	}
}


function otHtmlEncode(html)
{
	if (html == null || html === '') return '';
	html = html.toString(); //in case an Int was passed in

	html = html.replace(/&/g,'&amp;');
	html = html.replace(/</g, '&lt;');
	html = html.replace(/>/g, '&gt;');
	html = html.replace(/"/g, '&quot;');
	html = html.replace(/'/g, '&#39;');

	return html
}
function otJSEncode(js)
{
	if (js == null || js === '') return '';
	js = js.toString(); //in case an Int was passed in
    js = js.replace(/\\/g,"\\\\");
	js = js.replace(/'/g,"\\u0027");
	js = js.replace(/"/g, "\\u0022");
	js = js.replace(/\r/g, "\\r");
	js = js.replace(/\n/g,"\\n");

	return js;
}



/* DAD [INV-1605]: added HtmlDecode
   more info at http://blogs.msdn.com/aoakley/archive/2003/11/12/49645.aspx
   HtmlDecode http://lab.msdn.microsoft.com/annotations/htmldecode.js
   client side version of the useful Server.HtmlDecode method
   takes one string (encoded) and returns another (decoded) */
function otHtmlDecode(str)
{
      var out = "";
      if (str==null) return;

      var l = str.length;
      for (var i=0; i<l; i++)
      {
            var ch = str.charAt(i);

            if (ch == '&')
            {
                  var semicolonIndex = str.indexOf(';', i+1);

            if (semicolonIndex > 0)
            {
                        var entity = str.substring(i + 1, semicolonIndex);
                        if (entity.length > 1 && entity.charAt(0) == '#')
                        {
                              if (entity.charAt(1) == 'x' || entity.charAt(1) == 'X')
                                    ch = String.fromCharCode(eval('0'+entity.substring(1)));
                              else
                                    ch = String.fromCharCode(eval(entity.substring(1)));
                        }
                    else
                      {
                              switch (entity)
                              {
                                    case 'quot': ch = String.fromCharCode(0x0022); break;
                                    case 'amp': ch = String.fromCharCode(0x0026); break;
                                    case 'lt': ch = String.fromCharCode(0x003c); break;
                                    case 'gt': ch = String.fromCharCode(0x003e); break;
                                    case 'nbsp': ch = String.fromCharCode(0x00a0); break;
                                    case 'iexcl': ch = String.fromCharCode(0x00a1); break;
                                    case 'cent': ch = String.fromCharCode(0x00a2); break;
                                    case 'pound': ch = String.fromCharCode(0x00a3); break;
                                    case 'curren': ch = String.fromCharCode(0x00a4); break;
                                    case 'yen': ch = String.fromCharCode(0x00a5); break;
                                    case 'brvbar': ch = String.fromCharCode(0x00a6); break;
                                    case 'sect': ch = String.fromCharCode(0x00a7); break;
                                    case 'uml': ch = String.fromCharCode(0x00a8); break;
                                    case 'copy': ch = String.fromCharCode(0x00a9); break;
                                    case 'ordf': ch = String.fromCharCode(0x00aa); break;
                                    case 'laquo': ch = String.fromCharCode(0x00ab); break;
                                    case 'not': ch = String.fromCharCode(0x00ac); break;
                                    case 'shy': ch = String.fromCharCode(0x00ad); break;
                                    case 'reg': ch = String.fromCharCode(0x00ae); break;
                                    case 'macr': ch = String.fromCharCode(0x00af); break;
                                    case 'deg': ch = String.fromCharCode(0x00b0); break;
                                    case 'plusmn': ch = String.fromCharCode(0x00b1); break;
                                    case 'sup2': ch = String.fromCharCode(0x00b2); break;
                                    case 'sup3': ch = String.fromCharCode(0x00b3); break;
                                    case 'acute': ch = String.fromCharCode(0x00b4); break;
                                    case 'micro': ch = String.fromCharCode(0x00b5); break;
                                    case 'para': ch = String.fromCharCode(0x00b6); break;
                                    case 'middot': ch = String.fromCharCode(0x00b7); break;
                                    case 'cedil': ch = String.fromCharCode(0x00b8); break;
                                    case 'sup1': ch = String.fromCharCode(0x00b9); break;
                                    case 'ordm': ch = String.fromCharCode(0x00ba); break;
                                    case 'raquo': ch = String.fromCharCode(0x00bb); break;
                                    case 'frac14': ch = String.fromCharCode(0x00bc); break;
                                    case 'frac12': ch = String.fromCharCode(0x00bd); break;
                                    case 'frac34': ch = String.fromCharCode(0x00be); break;
                                    case 'iquest': ch = String.fromCharCode(0x00bf); break;
                                    case 'Agrave': ch = String.fromCharCode(0x00c0); break;
                                    case 'Aacute': ch = String.fromCharCode(0x00c1); break;
                                    case 'Acirc': ch = String.fromCharCode(0x00c2); break;
                                    case 'Atilde': ch = String.fromCharCode(0x00c3); break;
                                    case 'Auml': ch = String.fromCharCode(0x00c4); break;
                                    case 'Aring': ch = String.fromCharCode(0x00c5); break;
                                    case 'AElig': ch = String.fromCharCode(0x00c6); break;
                                    case 'Ccedil': ch = String.fromCharCode(0x00c7); break;
                                    case 'Egrave': ch = String.fromCharCode(0x00c8); break;
                                    case 'Eacute': ch = String.fromCharCode(0x00c9); break;
                                    case 'Ecirc': ch = String.fromCharCode(0x00ca); break;
                                    case 'Euml': ch = String.fromCharCode(0x00cb); break;
                                    case 'Igrave': ch = String.fromCharCode(0x00cc); break;
                                    case 'Iacute': ch = String.fromCharCode(0x00cd); break;
                                    case 'Icirc': ch = String.fromCharCode(0x00ce ); break;
                                    case 'Iuml': ch = String.fromCharCode(0x00cf); break;
                                    case 'ETH': ch = String.fromCharCode(0x00d0); break;
                                    case 'Ntilde': ch = String.fromCharCode(0x00d1); break;
                                    case 'Ograve': ch = String.fromCharCode(0x00d2); break;
                                    case 'Oacute': ch = String.fromCharCode(0x00d3); break;
                                    case 'Ocirc': ch = String.fromCharCode(0x00d4); break;
                                    case 'Otilde': ch = String.fromCharCode(0x00d5); break;
                                    case 'Ouml': ch = String.fromCharCode(0x00d6); break;
                                    case 'times': ch = String.fromCharCode(0x00d7); break;
                                    case 'Oslash': ch = String.fromCharCode(0x00d8); break;
                                    case 'Ugrave': ch = String.fromCharCode(0x00d9); break;
                                    case 'Uacute': ch = String.fromCharCode(0x00da); break;
                                    case 'Ucirc': ch = String.fromCharCode(0x00db); break;
                                    case 'Uuml': ch = String.fromCharCode(0x00dc); break;
                                    case 'Yacute': ch = String.fromCharCode(0x00dd); break;
                                    case 'THORN': ch = String.fromCharCode(0x00de); break;
                                    case 'szlig': ch = String.fromCharCode(0x00df); break;
                                    case 'agrave': ch = String.fromCharCode(0x00e0); break;
                                    case 'aacute': ch = String.fromCharCode(0x00e1); break;
                                    case 'acirc': ch = String.fromCharCode(0x00e2); break;
                                    case 'atilde': ch = String.fromCharCode(0x00e3); break;
                                    case 'auml': ch = String.fromCharCode(0x00e4); break;
                                    case 'aring': ch = String.fromCharCode(0x00e5); break;
                                    case 'aelig': ch = String.fromCharCode(0x00e6); break;
                                    case 'ccedil': ch = String.fromCharCode(0x00e7); break;
                                    case 'egrave': ch = String.fromCharCode(0x00e8); break;
                                    case 'eacute': ch = String.fromCharCode(0x00e9); break;
                                    case 'ecirc': ch = String.fromCharCode(0x00ea); break;
                                    case 'euml': ch = String.fromCharCode(0x00eb); break;
                                    case 'igrave': ch = String.fromCharCode(0x00ec); break;
                                    case 'iacute': ch = String.fromCharCode(0x00ed); break;
                                    case 'icirc': ch = String.fromCharCode(0x00ee); break;
                                    case 'iuml': ch = String.fromCharCode(0x00ef); break;
                                    case 'eth': ch = String.fromCharCode(0x00f0); break;
                                    case 'ntilde': ch = String.fromCharCode(0x00f1); break;
                                    case 'ograve': ch = String.fromCharCode(0x00f2); break;
                                    case 'oacute': ch = String.fromCharCode(0x00f3); break;
                                    case 'ocirc': ch = String.fromCharCode(0x00f4); break;
                                    case 'otilde': ch = String.fromCharCode(0x00f5); break;
                                    case 'ouml': ch = String.fromCharCode(0x00f6); break;
                                    case 'divide': ch = String.fromCharCode(0x00f7); break;
                                    case 'oslash': ch = String.fromCharCode(0x00f8); break;
                                    case 'ugrave': ch = String.fromCharCode(0x00f9); break;
                                    case 'uacute': ch = String.fromCharCode(0x00fa); break;
                                    case 'ucirc': ch = String.fromCharCode(0x00fb); break;
                                    case 'uuml': ch = String.fromCharCode(0x00fc); break;
                                    case 'yacute': ch = String.fromCharCode(0x00fd); break;
                                    case 'thorn': ch = String.fromCharCode(0x00fe); break;
                                    case 'yuml': ch = String.fromCharCode(0x00ff); break;
                                    case 'OElig': ch = String.fromCharCode(0x0152); break;
                                    case 'oelig': ch = String.fromCharCode(0x0153); break;
                                    case 'Scaron': ch = String.fromCharCode(0x0160); break;
                                    case 'scaron': ch = String.fromCharCode(0x0161); break;
                                    case 'Yuml': ch = String.fromCharCode(0x0178); break;
                                    case 'fnof': ch = String.fromCharCode(0x0192); break;
                                    case 'circ': ch = String.fromCharCode(0x02c6); break;
                                    case 'tilde': ch = String.fromCharCode(0x02dc); break;
                                    case 'Alpha': ch = String.fromCharCode(0x0391); break;
                                    case 'Beta': ch = String.fromCharCode(0x0392); break;
                                    case 'Gamma': ch = String.fromCharCode(0x0393); break;
                                    case 'Delta': ch = String.fromCharCode(0x0394); break;
                                    case 'Epsilon': ch = String.fromCharCode(0x0395); break;
                                    case 'Zeta': ch = String.fromCharCode(0x0396); break;
                                    case 'Eta': ch = String.fromCharCode(0x0397); break;
                                    case 'Theta': ch = String.fromCharCode(0x0398); break;
                                    case 'Iota': ch = String.fromCharCode(0x0399); break;
                                    case 'Kappa': ch = String.fromCharCode(0x039a); break;
                                    case 'Lambda': ch = String.fromCharCode(0x039b); break;
                                    case 'Mu': ch = String.fromCharCode(0x039c); break;
                                    case 'Nu': ch = String.fromCharCode(0x039d); break;
                                    case 'Xi': ch = String.fromCharCode(0x039e); break;
                                    case 'Omicron': ch = String.fromCharCode(0x039f); break;
                                    case 'Pi': ch = String.fromCharCode(0x03a0); break;
                                    case ' Rho ': ch = String.fromCharCode(0x03a1); break;
                                    case 'Sigma': ch = String.fromCharCode(0x03a3); break;
                                    case 'Tau': ch = String.fromCharCode(0x03a4); break;
                                    case 'Upsilon': ch = String.fromCharCode(0x03a5); break;
                                    case 'Phi': ch = String.fromCharCode(0x03a6); break;
                                    case 'Chi': ch = String.fromCharCode(0x03a7); break;
                                    case 'Psi': ch = String.fromCharCode(0x03a8); break;
                                    case 'Omega': ch = String.fromCharCode(0x03a9); break;
                                    case 'alpha': ch = String.fromCharCode(0x03b1); break;
                                    case 'beta': ch = String.fromCharCode(0x03b2); break;
                                    case 'gamma': ch = String.fromCharCode(0x03b3); break;
                                    case 'delta': ch = String.fromCharCode(0x03b4); break;
                                    case 'epsilon': ch = String.fromCharCode(0x03b5); break;
                                    case 'zeta': ch = String.fromCharCode(0x03b6); break;
                                    case 'eta': ch = String.fromCharCode(0x03b7); break;
                                    case 'theta': ch = String.fromCharCode(0x03b8); break;
                                    case 'iota': ch = String.fromCharCode(0x03b9); break;
                                    case 'kappa': ch = String.fromCharCode(0x03ba); break;
                                    case 'lambda': ch = String.fromCharCode(0x03bb); break;
                                    case 'mu': ch = String.fromCharCode(0x03bc); break;
                                    case 'nu': ch = String.fromCharCode(0x03bd); break;
                                    case 'xi': ch = String.fromCharCode(0x03be); break;
                                    case 'omicron': ch = String.fromCharCode(0x03bf); break;
                                    case 'pi': ch = String.fromCharCode(0x03c0); break;
                                    case 'rho': ch = String.fromCharCode(0x03c1); break;
                                    case 'sigmaf': ch = String.fromCharCode(0x03c2); break;
                                    case 'sigma': ch = String.fromCharCode(0x03c3); break;
                                    case 'tau': ch = String.fromCharCode(0x03c4); break;
                                    case 'upsilon': ch = String.fromCharCode(0x03c5); break;
                                    case 'phi': ch = String.fromCharCode(0x03c6); break;
                                    case 'chi': ch = String.fromCharCode(0x03c7); break;
                                    case 'psi': ch = String.fromCharCode(0x03c8); break;
                                    case 'omega': ch = String.fromCharCode(0x03c9); break;
                                    case 'thetasym': ch = String.fromCharCode(0x03d1); break;
                                    case 'upsih': ch = String.fromCharCode(0x03d2); break;
                                    case 'piv': ch = String.fromCharCode(0x03d6); break;
                                    case 'ensp': ch = String.fromCharCode(0x2002); break;
                                    case 'emsp': ch = String.fromCharCode(0x2003); break;
                                    case 'thinsp': ch = String.fromCharCode(0x2009); break;
                                    case 'zwnj': ch = String.fromCharCode(0x200c); break;
                                    case 'zwj': ch = String.fromCharCode(0x200d); break;
                                    case 'lrm': ch = String.fromCharCode(0x200e); break;
                                    case 'rlm': ch = String.fromCharCode(0x200f); break;
                                    case 'ndash': ch = String.fromCharCode(0x2013); break;
                                    case 'mdash': ch = String.fromCharCode(0x2014); break;
                                    case 'lsquo': ch = String.fromCharCode(0x2018); break;
                                    case 'rsquo': ch = String.fromCharCode(0x2019); break;
                                    case 'sbquo': ch = String.fromCharCode(0x201a); break;
                                    case 'ldquo': ch = String.fromCharCode(0x201c); break;
                                    case 'rdquo': ch = String.fromCharCode(0x201d); break;
                                    case 'bdquo': ch = String.fromCharCode(0x201e); break;
                                    case 'dagger': ch = String.fromCharCode(0x2020); break;
                                    case 'Dagger': ch = String.fromCharCode(0x2021); break;
                                    case 'bull': ch = String.fromCharCode(0x2022); break;
                                    case 'hellip': ch = String.fromCharCode(0x2026); break;
                                    case 'permil': ch = String.fromCharCode(0x2030); break;
                                    case 'prime': ch = String.fromCharCode(0x2032); break;
                                    case 'Prime': ch = String.fromCharCode(0x2033); break;
                                    case 'lsaquo': ch = String.fromCharCode(0x2039); break;
                                    case 'rsaquo': ch = String.fromCharCode(0x203a); break;
                                    case 'oline': ch = String.fromCharCode(0x203e); break;
                                    case 'frasl': ch = String.fromCharCode(0x2044); break;
                                    case 'euro': ch = String.fromCharCode(0x20ac); break;
                                    case 'image': ch = String.fromCharCode(0x2111); break;
                                    case 'weierp': ch = String.fromCharCode(0x2118); break;
                                    case 'real': ch = String.fromCharCode(0x211c); break;
                                    case 'trade': ch = String.fromCharCode(0x2122); break;
                                    case 'alefsym': ch = String.fromCharCode(0x2135); break;
                                    case 'larr': ch = String.fromCharCode(0x2190); break;
                                    case 'uarr': ch = String.fromCharCode(0x2191); break;
                                    case 'rarr': ch = String.fromCharCode(0x2192); break;
                                    case 'darr': ch = String.fromCharCode(0x2193); break;
                                    case 'harr': ch = String.fromCharCode(0x2194); break;
                                    case 'crarr': ch = String.fromCharCode(0x21b5); break;
                                    case 'lArr': ch = String.fromCharCode(0x21d0); break;
                                    case 'uArr': ch = String.fromCharCode(0x21d1); break;
                                    case 'rArr': ch = String.fromCharCode(0x21d2); break;
                                    case 'dArr': ch = String.fromCharCode(0x21d3); break;
                                    case 'hArr': ch = String.fromCharCode(0x21d4); break;
                                    case 'forall': ch = String.fromCharCode(0x2200); break;
                                    case 'part': ch = String.fromCharCode(0x2202); break;
                                    case 'exist': ch = String.fromCharCode(0x2203); break;
                                    case 'empty': ch = String.fromCharCode(0x2205); break;
                                    case 'nabla': ch = String.fromCharCode(0x2207); break;
                                    case 'isin': ch = String.fromCharCode(0x2208); break;
                                    case 'notin': ch = String.fromCharCode(0x2209); break;
                                    case 'ni': ch = String.fromCharCode(0x220b); break;
                                    case 'prod': ch = String.fromCharCode(0x220f); break;
                                    case 'sum': ch = String.fromCharCode(0x2211); break;
                                    case 'minus': ch = String.fromCharCode(0x2212); break;
                                    case 'lowast': ch = String.fromCharCode(0x2217); break;
                                    case 'radic': ch = String.fromCharCode(0x221a); break;
                                    case 'prop': ch = String.fromCharCode(0x221d); break;
                                    case 'infin': ch = String.fromCharCode(0x221e); break;
                                    case 'ang': ch = String.fromCharCode(0x2220); break;
                                    case 'and': ch = String.fromCharCode(0x2227); break;
                                    case 'or': ch = String.fromCharCode(0x2228); break;
                                    case 'cap': ch = String.fromCharCode(0x2229); break;
                                    case 'cup': ch = String.fromCharCode(0x222a); break;
                                    case 'int': ch = String.fromCharCode(0x222b); break;
                                    case 'there4': ch = String.fromCharCode(0x2234); break;
                                    case 'sim': ch = String.fromCharCode(0x223c); break;
                                    case 'cong': ch = String.fromCharCode(0x2245); break;
                                    case 'asymp': ch = String.fromCharCode(0x2248); break;
                                    case 'ne': ch = String.fromCharCode(0x2260); break;
                                    case 'equiv': ch = String.fromCharCode(0x2261); break;
                                    case 'le': ch = String.fromCharCode(0x2264); break;
                                    case 'ge': ch = String.fromCharCode(0x2265); break;
                                    case 'sub': ch = String.fromCharCode(0x2282); break;
                                    case 'sup': ch = String.fromCharCode(0x2283); break;
                                    case 'nsub': ch = String.fromCharCode(0x2284); break;
                                    case 'sube': ch = String.fromCharCode(0x2286); break;
                                    case 'supe': ch = String.fromCharCode(0x2287); break;
                                    case 'oplus': ch = String.fromCharCode(0x2295); break;
                                    case 'otimes': ch = String.fromCharCode(0x2297); break;
                                    case 'perp': ch = String.fromCharCode(0x22a5); break;
                                    case 'sdot': ch = String.fromCharCode(0x22c5); break;
                                    case 'lceil': ch = String.fromCharCode(0x2308); break;
                                    case 'rceil': ch = String.fromCharCode(0x2309); break;
                                    case 'lfloor': ch = String.fromCharCode(0x230a); break;
                                    case 'rfloor': ch = String.fromCharCode(0x230b); break;
                                    case 'lang': ch = String.fromCharCode(0x2329); break;
                                    case 'rang': ch = String.fromCharCode(0x232a); break;
                                    case 'loz': ch = String.fromCharCode(0x25ca); break;
                                    case 'spades': ch = String.fromCharCode(0x2660); break;
                                    case 'clubs': ch = String.fromCharCode(0x2663); break;
                                    case 'hearts': ch = String.fromCharCode(0x2665); break;
                                    case 'diams': ch = String.fromCharCode(0x2666); break;
                                    default: ch = ''; break;
                              }
                        }
                        i = semicolonIndex;
                  }
            }

            out += ch;
      }

      return out;

}
// end function otHtmlDecode(s)

function tryFocus(field)
{
	try {field.focus()}
	catch (e) {}
}

function otHasOwnProperty(testArray, key)
{
	//needed because: 1) some 3rd party javascript modifies Array.prototype
	//2) not every browser has the "hasOwnProperty" method :(
	if (testArray.hasOwnProperty)
		return testArray.hasOwnProperty(key)
	else
		return (testArray[key] != Array.prototype[key]);
}


function removeZerosFromNum(str) {
	// removes any zeros on the left or the right of the string
	var decPos = str.indexOf('.');
	var leftZero = 0;  // first position in the string
	var rightZero = str.length-1;  // last position in the string

	if (decPos == -1)
		decPos = rightZero; // if there's no decimal then it's the rightmost character

	// take away all zeros except the one immediately to the left of the decimal
	while (str.substr(leftZero,1) == '0' && leftZero < decPos - 1) {
		leftZero++;
	}

	// take away all zeros except the one immediately to the right of the decimal
	while (str.substr(rightZero,1) == '0' && rightZero > decPos + 1) {
		rightZero--;
	}

	return str.substr(leftZero,rightZero - leftZero + 1);
}

function getDecShift(instr) {
	var decPos = instr.indexOf('.');
	if (decPos == -1) {
		return 0;
	}
	else {
		// how many places to left of end is the decimal
		return (instr.length - decPos - 1);
	}
}

function preciseMultiply(a,b) {

	// NOTE: This will return garbage if you have case where you multiply
	// 698asdas.sda * 123asd123.asd23 or some such.  Whereas calling parseFloat()
	// on the 698asdas.sda will give you a valid number.  Reason is that I do not
	// want to convert the string to a float beacuse I would potentially lose
	// the accuracy of the input.  So if you're going to use this you should make
	// sure that you're passing in valid numbers.  If you pass in garbage that
	// definitely isn't a number, I do return NaN - so asdasd * 123 = NaN.
	if (isNaN(parseFloat(a)) || isNaN(parseFloat(b))) {
		return(NaN);
	}

	var m1 = removeZerosFromNum(a.toString());
	var m2 = removeZerosFromNum(b.toString());

	var outstr1, outstr2, shift, resultStr;
	shift = getDecShift(m1);
	shift += getDecShift(m2);

	outstr1 = m1.replace('.','');
	outstr2 = m2.replace('.','');

	var tmpMult = (parseInt(outstr1,10) * parseInt(outstr2,10)).toString();

	// now shift back if needed
	if (shift == 0) {
		resultStr = tmpMult;
	}
	else {
		if (tmpMult.length-shift > 0) {
			resultStr =  tmpMult.substr(0,tmpMult.length-shift) + '.' + tmpMult.substr(tmpMult.length - shift)
		}
		else {
			resultStr = '.';
			for (var f = 0; f < shift - tmpMult.length; f++) {
				resultStr += '0';
			}
			resultStr += tmpMult;
		}
	}
	return (resultStr);
}


//simply displays the full text in a popup a bit above the span, with a slight delay before opening the popup
function displayShort(stringVar, numChars)
{
	if (stringVar.length <= numChars) {
		return stringVar;
	}
	//note, come back and retest this after the 1/19 build
	//if (typeof(otShowPopupHelp) != 'undefined') {
	//	var shortString = '<span onmouseover="otShowPopupHelp(\'' + stringVar + '\', this, {title:\'\',width: \'300px\', showClose: false, isRightClickMenu: false, yOffset: -95, xOffset: 70, delay: 300});" onmouseout="otHidePopupHelp();">' + stringVar.substring(0, numChars) + '...</span>';
	//} else {
		var shortString = '<span title="' + stringVar + '">' + stringVar.substring(0, numChars) + '...</span>';
	//}
	return shortString;
}

//safari doesn't have localeCompare :(
if (!String.prototype.localeCompare) String.prototype.localeCompare = function (string2) {
	//just use a normal string compare.
	var string1 = this;
	if (string1 == string2) return 0;
	return (string1 < string2) ? -1 : 1;
}

//IE7 broke window.prompt for some goofy reason
if (document.all && window.XMLHttpRequest && window.showModalDialog) {
	//using ie7 or above
	window.oldprompt = window.prompt;

	//override window.prompt
	window.prompt = function(message, defaultValue) {
		var url = '/common/dialog.asp'
		url += '?message=' + escape(message)
		if (defaultValue != null) {
			url += '&defaultValue=' + escape(defaultValue)
		}
		url+= '&rnd=' + escape(new Date().valueOf());

		var result = window.showModalDialog(url, '', 'dialogHeight:300px;scroll:0;');
		return result;
	}
}


function logJsError_getstack(currFunction) {
	var output = '';
	var maxCodeLength = 400;
	var currDepth = 0;
	while (currFunction != null && currDepth++ < 5 ) {
		try {
			var re = / [^ (]+/; //The func name will have a space before it.
			var name = re.exec(currFunction.toString())[0];
			if (name == ' anonymous' || name == ' command' || name == ' commandOne' || name == ' commandTwo') {
				var funcString = currFunction.toString();
				var code = funcString.substring(funcString .indexOf("{"), funcString.length);
				var label = " Anonymous function: ";
				if (name == ' command' || name == ' commandOne' || name == ' commandTwo')
					label = " Command: ";
				if (code.length < maxCodeLength) {
					output += label + code ;
				} else {
					output += label + code.substring(0, maxCodeLength) + "...";
				}
			} else {
				var re = / [^)]+/;
				var code = re.exec(currFunction.toString())[0];
				output += " function:" + code + ')';
			}
		} catch (e) {
			output += " unknown";
		}

		try {
			if (currFunction.arguments && currFunction.arguments.length)
			{
				output+= '\r\n\t Arguments: [';
				for (var i=0; i<currFunction.arguments.length;i++)
				{
					if (i > 0) {
						output += ',';
					}
					output+= currFunction.arguments[i];
				}
				output += ']';
			}
			output += '\r\n';
		} catch(e) {
			//catch nothing
		}

		try {
			currFunction = currFunction.caller;
		} catch (e) {
			//nothing to catch
		}

	}
	//if (currFunction == null) output += " global window"; // not in a function
	return output;
}


/*
 * Originally from: http://ajaxian.com/archives/getting-a-javascript-stracktrace-in-any-browser
 * Modifications:
 *   - using our _name attribute as function name if found
 */
if (!CNQR) {
    CNQR = {};
}

(function ()
{
    CNQR.getStackTrace = (function ()
    {
        var mode;


        try {(0)()} catch (e)
        {
            mode = e.stack ? "Firefox" : window.opera ? "Opera" : "Other";
        }


        switch (mode)
        {
            case "Firefox": return function ()
            {
                try {(0)()} catch (e)
                {
                    return e.stack
                    .replace(/^.*?\n/, "")
                    .replace(/(?:\n@:0)?\s+$/m, "")
                    .replace(/^\(/gm, "{anonymous}(")
                    .split("\n");
                }
            };

            case "Opera": return function ()
            {
                try {(0)()} catch (e)
                {
                    var lines = e.message.split("\n"),
                        ANON = "{anonymous}",
                        lineRE = /Line\s+(\d+).*?in\s+(http\S+)(?:.*?in\s+function\s+(\S+))?/i,
                        i,
                        j,
                        len;

                    for (i = 4, j = 0, len = lines.length; i < len; i += 2)
                    {
                        if (lineRE.test(lines[i]))
                        {
                            lines[j++] = (RegExp.$3 ? RegExp.$3 + "()@" + RegExp.$2 + RegExp.$1 : ANON + RegExp.$2 + ":" + RegExp.$1) + " -- " + lines[i+1].replace(/^\s+/, "");
                        }
                    }

                    lines.splice(j, lines.length - j);

                    return lines;
                }
            };

            default: return function ()
            {
                var curr = arguments.callee.caller,
                    FUNC = "function",
                    ANON = "{anonymous}",
                    fnRE = /function\s*([\w\-$]+)?\s*\(/i,
                    stack = [],
                    j = 0,
                    fn,
                    args,
                    i;

                while (curr)
                {
                    //debugger;
                    if (curr._name)
                    {
                        fn = curr._name;
                    }
                    else
                    {
                        fn = fnRE.test(curr.toString()) ? RegExp.$1 || ANON : ANON;
                    }

                    args = stack.slice.call(curr.arguments);

                    i = args.length;


                    while (i--)
                    {
                        switch (typeof args[i])
                        {
                            case "string":
                                args[i] = '"' + args[i].replace(/"/g,'\\"') + '"';
                                break;

                            case "function":
                                args[i] = FUNC;
                                break;
                        }
                    }

                    stack[j++] = fn + "(" + args.join() + ")";

                    curr = curr.caller;
                }

                return stack;
            };
        }
    })();
})();
/*
 * Originally from http://helephant.com/2007/05/diy-javascript-stack-trace/
 * Modifications:
 *   - using our _name attribute as function name if found
 *   - for anonymous functions, appending the whole function body to stack trace
 */
Function.prototype.trace = function()
{
    var counter = 0;
	var trace = [];
    var current = this;
    while(current && counter < 15)
    {
        trace.push(current.signature());
        current = current.caller;
		counter++;
    }
    return trace;
}
Function.prototype.signature = function()
{
    var signature = {
        name: this.getName(),
        params: [],
        toString: function()
        {
            var params = this.params.length > 0 ?
                "'" + this.params.join("', '") + "'" : "";
            return this.name + "(" + params + ")"
        }
    };
    if(this.arguments)
    {
        for(var x=0; x<this.arguments.length; x++)
            signature.params.push(this.arguments[x]);
    }
    return signature;
}
Function.prototype.getName = function()
{
    if(this.name)
        return this.name;
    if(this._name)
        return this._name;
    var definition = this.toString().split("\n")[0];
    var exp = /^function ([^\s(]+).+/;
    if(exp.test(definition))
        return definition.split("\n")[0].replace(exp, "$1") || "anonymous:"+this.toString();
    return "anonymous:" + this.toString();
}

function logJsError(msg, url, ln, stack, cat, subcat) {

	try {
//		if (!stack) stack = logJsError_getstack(logJsError.caller);
        if (!stack) stack = logJsError.caller.trace().join("\r\n");
	}
	catch(e)
	{
	   stack = 'stack error: ';
	   if (e.name) stack += e.name + ": ";
	   if (e.message) stack += e.message + " ";
	   if (e.description) stack += "(" + e.description + ")";
	   stack += "\r\n\r\ntrying alternate method to get stack trace...\r\n\r\n";
	   try {
	       stack += CNQR.getStackTrace().join("\r\n");
	   }
	   catch(e2)
	   {
	       stack += 'stack error: ';
           if (e2.name) stack += e2.name + ": ";
           if (e2.message) stack += e2.message + " ";
           if (e2.description) stack += "(" + e2.description + ")";
	   }
	}
    try {
	    var handled = "true";
        if (CNQR && CNQR.debug) {
            if (CNQR.debug.lastAjaxRequest) {
                stack += "\r\n\r\nlastAjaxRequest: " + CNQR.debug.lastAjaxRequest;
            }
            if (CNQR.debug.lastAjaxRequestTime) {
                var delta = new Date().getTime() - CNQR.debug.lastAjaxRequestTime.getTime();
                stack += "\r\nlastAjaxRequestTime: " + CNQR.debug.lastAjaxRequestTime + " (" + delta + "ms ago)";
            }

            if (CNQR.debug.lastAjaxResponse) {
                stack += "\r\nlastAjaxResponse: " + CNQR.debug.lastAjaxResponse;
            }

            if (CNQR.debug.getDebugMessages) {
                var msgs = CNQR.debug.getDebugMessages();
                if (msgs.length > 0) {
                    stack += "\r\n\r\nlast debug messages:\r\n";
                    for (var i=0; i < msgs.length; i++) {
                        stack += i + ": " + msgs[i] + "\r\n";
                    }
                }
            }
            if (CNQR.debug.errorDlgShown)
            {
			    var handled = "false";
			    CNQR.debug.errorDlgShown = false;
            }
        }

	    var strValues = "errDesc=" + encodeURIComponent(msg);
        strValues += "&ln=" + ln;
        strValues += "&qs=" + encodeURIComponent(location.search);
        strValues += "&u=" + encodeURIComponent(location.pathname);
        strValues += "&r=" + encodeURIComponent(document.referrer);
        strValues += "&s=" + encodeURIComponent(stack);
        strValues += "&h=" + encodeURIComponent(handled);
        if (cat) {
            strValues += "&cat=" + encodeURIComponent(cat);
        }
        if (subcat) {
            strValues += "&subCat=" + encodeURIComponent(subcat);
        }

	    // don't report the error if it's identical to one we've already reported 3 times
	    if (!CQJSerrors[strValues]) CQJSerrors[strValues] = 1;

	    if (CQJSerrors[strValues] < 3) {
		    CQJSerrors[strValues]++;

	        if (window.Ajax && Ajax.Request) {
			    new Ajax.Request('/errors/jsError.asp', {method: 'post', parameters: strValues});
	        }
	        else {
			    var callBackImg = new Image();
	            callBackImg.src = "/errors/jsError.asp?image=1&" + strValues;
		    }
	    }
	 }catch(ex){}
	 return false; //so user still sees the error

}

try {
	window.onerror = logJsError;
}
catch(er) {}

function addCSSFile(src) {
	if (!$(src)) {
		var element=document.createElement("link");
		element.setAttribute("rel", "stylesheet");
		element.setAttribute("type", "text/css");
		element.setAttribute("href", src);
		element.id = src;
		document.getElementsByTagName("head")[0].appendChild(element);
	}
}

function addScript(src, callback) {

	if (window.otCacheKilla) {
		src+= (src.indexOf('?') >=0) ? '&' : '?';
		src+= 'cachekilla=' + window.otCacheKilla;
	}

	var scripts = document.getElementsByTagName('script');

	if (!window['debug_scripts']) {
		for (var i=0; i<scripts.length; i++) {
			if (scripts[i].getAttribute('src') == src) {
				//script already exists
				if (callback && callback.constructor == Function)
				callback();
				return;
			}
		}
	}

	if( document.createElement && document.childNodes ) {
		var scriptElem = document.createElement('script');

		if (callback && callback.constructor == Function) {
			scriptElem.onload = scriptElem.onreadystatechange = function() {
				//OTDebugWrite('Readystate for: ' + src + ' is: ' + scriptElem.readyState);
				if (scriptElem.readyState && scriptElem.readyState != 'loaded' && scriptElem.readyState != 'complete')
				{
					return;
				}
				scriptElem.onreadystatechange = scriptElem.onload = null;
				callback();
			}

			scriptElem.onerror = function() {
				OTDebugWrite('Error loading javascript file: ' + src);
				var fn = scriptElem.onload;
				if (fn) {
					fn()
				};
			}
		};
		scriptElem.setAttribute('src', src);
		scriptElem.setAttribute('type','text/javascript');
		document.getElementsByTagName('head')[0].appendChild(scriptElem);
	}
	else {
		// inserting via DOM fails in Safari 2.0, so brute force approach
		document.write('<scr' + 'ipt type="text/javascript" src="' + src + '"></scr' + 'ipt>');
	}
}

function addAllScripts(htmlOrArray, callback) {
	//This will append all scripts to a page, and will fire the callback when all scripts are loaded
	//Input is either an html string or an array

	var arrScriptSrc = [];
	if (htmlOrArray.constructor == Array)
	{
		for (var i=0,len=htmlOrArray.length; i<len; ++i)
		{
			arrScriptSrc.push({src:htmlOrArray[i], completed:false});
		}
	}
	else //extract all scripts from the html string
	{
		var myRe = /<script[^>]*\ssrc=['\"]([^'\"]*?)['\"][^\>]*\/?\>/img;
		while ((myArray = myRe.exec(htmlOrArray)) != undefined) {
			arrScriptSrc.push({src:myArray[1], completed:false});
		}
	}
	var itemCallback = function (_arrScriptSrc, _j) {
		//set up a closure so these get wrapped in the function that is returned
		var arrScriptSrc = _arrScriptSrc;
		var j = _j;
		return function() {
			//OTDebugWrite(j + ':' + arrScriptSrc[j].src);
			arrScriptSrc[j].completed = true;
			if (callback){ //when all scripts have been run, fire the callback
				for (var i=0;i<arrScriptSrc.length; i++) {
					if (!arrScriptSrc[i].completed)
						return;
				}
				callback()
			}
		}
	}

	if (arrScriptSrc.length > 0) {
		//OTDebugWrite('appending: ' + arrScriptSrc.length)
		for (var i=0; i<arrScriptSrc.length; i++) {
			addScript(arrScriptSrc[i].src, itemCallback(arrScriptSrc, i));
		}
		return;
	}
	if (callback && callback.constructor == Function) {
		callback();
	}

}

//add checkbox class to all reports...
//if (document.all && window.attachEvent){window.attachEvent("onload", function () {var tbls = document.getElementsByTagName("table");for (var i=0; i<tbls.length; i++){var t = tbls[i];if (t.className != null && t.className.indexOf("reporttable")){var chks = t.getElementsByTagName("input");for (var c=0; c < chks.length; c++) {if (chks[c].type == "checkbox") {chks[c].className+= " checkbox"};}}}});}


/*   contents of cookies.js */


var exp = new Date();
exp.setTime(exp.getTime() + 31536000000); //(365*24*60*60*1000));

function GetCookie (name, subCookieName)
{
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var retCook = null;

	function getCookieVal (offset)
	{
		var endstr = document.cookie.indexOf (";", offset);
		if (endstr == -1) {
			endstr = document.cookie.length;
		}
		return unescape(document.cookie.substring(offset, endstr));
	}

	var i = 0;
	while (i < clen)
	{
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg)
		{
			retCook = getCookieVal (j);
			break;
		}
		else
			i = document.cookie.indexOf(" ", i) + 1;

		if (i == 0) break;
	}

	if (retCook && subCookieName)
	{
		retCook = getCookieDict(retCook)[subCookieName];
	}

	return retCook;
}

function getCookieDict(cookieVal)
{
	var dict = new Object;
	if (cookieVal)
	{
		var arrSubCooks = cookieVal.split('&');
		for (var i=0; i < arrSubCooks.length; i++)
		{
			var subCooks = arrSubCooks[i].split('=');
			dict[subCooks[0]] = subCooks[1];
		}
	}
	return dict;
}

function SetAndRefresh(name, value)
{
	SetCookie(name, value, exp, '/');
	document.location.reload();
}

function SetCookie (name, value) {

	if (window.disableCookies) return;

	var argv = SetCookie.arguments;
	var argc = SetCookie.arguments.length;
	var expires = (argc > 2) ? argv[2] : null;
	var path = (argc > 3) ? argv[3] : null;
	var domain = (argc > 4) ? argv[4] : null;
	var secure = (argc > 5) ? argv[5] : false;
	if (value == '' || value == null) expires = new Date('1999-08-15');
// may need to escape/replace bad character in value
	document.cookie = name + "=" + value +
		((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
		((path == null) ? ";path=/" : ("; path=" + path)) +
		((domain == null) ? "" : ("; domain=" + domain)) +
		((secure == true) ? "; secure" : "");
}


function SetSubCookie(name, subCookieName, value, expires) {

	if (window.disableCookies) return;

	var cookieVal = GetCookie(name)
	if (value == '')
		value = null;

	var cookieDict = getCookieDict(cookieVal);
	cookieDict[subCookieName] = value;
	cookieVal = ''; //blank it out
	for (var subCook in cookieDict)
	{
		if (cookieDict[subCook] != null)
		{
			cookieVal += (cookieVal.length > 0) ? '&' : '';
			cookieVal += subCook + '=' + cookieDict[subCook];
		}
	}
//	SetCookie(name, cookieVal, expires)
	document.cookie = name + "=" + cookieVal +
		((expires == null) ? "" : ("; expires=" + expires.toGMTString()))
}

function DeleteCookie (name)
{
	var exp = new Date();
	exp.setTime (exp.getTime() - 1);
	var cval = GetCookie (name);
	document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}


/* end cookies .js */

//escape() is not utf-8 compliant, so use encodeURIComponent instead when site is configured for UTF-8
(function () {
	var charset = (document.charset || document.characterSet) //IE version||FFox
	if (charset == "UTF-8") {
		window.oldEscape = window.oldEscape || window.escape;
		window.escape = window.encodeURIComponent;
	}
})();

///****************************************************BEGIN-Idle and Session TimeOut****************************************************************************//

if (window.sessionLockTime > 0) {
	var setSessionLock = false;
	var currIdleTime = 0;
	addEvent(window, 'load', function(event) {
		//Increment the idle time counter every minute.
		var idleInterval = setInterval('timerIncrement()', 60000); // 1 minute

		//Zero the idle timer on mouse movement.
		addEvent(document.body, 'mousemove', function(event) {
			currIdleTime = 0;
		});
		//Zero the idle timer on keypress movement.
		addEvent(document.body, 'keypress', function(event) {
			currIdleTime = 0;
		});
		//Zero the idle timer on on body click movement.
		addEvent(document.body, 'click', function(event) {
			currIdleTime = 0;
		});
	});
}

//sessionLockTime - Declared in inc_pagetempalate.asp
//sessionLogoutTime - Declared in inc_pagetempalate.asp
function timerIncrement() {
	if (window.sessionLockTime)
	{
		currIdleTime = currIdleTime + 60; //incrementing in seconds
		if (currIdleTime > window.sessionLockTime && setSessionLock == false) { // Idle Time - Lock
			//set session("locked") = true
			var URL = '/javascript/service/LockSession.asp';
			new Ajax.Request(URL,
				{
					method: 'get',
					onSuccess: function(transport) {
						var response = transport.responseText || "no response text";
						if (response == 'set') { ////Will set the lock and also set setSessionLock = true to avoid opening the div multiple times on the same window.
							setSessionLock = true;
							UserSessionLockDiv();
						}
						else if (response == 'notset') {//Verify if the session is not in use and will not set the lock
							setSessionLock = false;
							currIdleTime = 0;
						}
						else if (response == 'alreadyset') {//Verify if the session is not in use and will not set the lock
							setSessionLock = true;
							UserSessionLockDiv();
						}
					}
				});
		}
		if (currIdleTime > window.sessionLogoutTime) { // Time out - Logout
			window.location.replace('/errors/loggedout.asp');
		}
	}
}

function UserSessionLockDiv() {

	var title = 'Your session has expired.Please click ok to login and go back to the last page.';
	// create contents of the dialog box
	var link = '/travel/popup_user_reauthentication.asp';
	var dialogBoxContents = '';
	dialogBoxContents += '<table width="100%"><tr>';
	dialogBoxContents += '<td align="center" valign="middle" width="100%"><b>' + title + '</b></td>';
	dialogBoxContents += '</td></tr><tr>';
	dialogBoxContents += '<td align="center" valign="middle" height="100%">';
	dialogBoxContents += '<a href="/errors/loggedout.asp"><b>Logout</b></a>';
	dialogBoxContents += '</td></tr><tr>';
	dialogBoxContents += '<td align="center" valign="middle" height="100%">';
	dialogBoxContents += '</td></tr></table>';
	CNQR.MessageBox.confirm(dialogBoxContents, {
		title: 'Login Again'
							, icon: CNQR.MessageBox.NoIcon
							, buttons: CNQR.MessageBox.OK
							, onButtonClick: function(btnConfig) {

								if (btnConfig.value == 'OK') {
									LoginReauthenticationPopup(link);
								}
							}
							, width: 500
							, maxHeight: 500
	}
			);
}

function LoginReauthenticationPopup(p) {
	var y = document.URL;
	var url = p + '?url=' + y + '&status=begin';
	var left = (screen.width - 500) / 2;
	var top = (screen.height - 200) / 2;
	var params = 'width=500';
	params += ', height=200';
	params += ', top=' + top + ', left=' + left;
	params += ', directories=no';
	params += ', location=no';
	params += ', menubar=no';
	params += ', resizable=no';
	params += ', scrollbars=no';
	params += ', status=no';
	params += ', toolbar=no';

	var newwindow = window.open(url, 'Login', params);
	if (window.focus) { newwindow.focus() }
}

//****************************************************END-Idle and Session TimeOut****************************************************************************//